import 'dart:io';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter_yres/model/shop/hdk_list_model.dart';
import 'package:flutter_yres/tool/LoadingUtil.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_yres/pages/event/LoginEvent.dart';
import 'package:flutter_yres/pages/login/login_page.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_alibc/flutter_alibc.dart';
import 'package:flutter_alibc/alibc_const_key.dart';
import './goodShare.dart';

class ShopDetailPage extends StatefulWidget {
  HDKListModelData hdkmodel;

  ShopDetailPage({Key key, this.hdkmodel}) : super(key: key);

  @override
  _ShopDetailPageState createState() => _ShopDetailPageState(hdkmodel);
}

class _ShopDetailPageState extends State<ShopDetailPage> {
  WebViewController _controller;
  double _htmlHeight = 1200;
  var token;
  bool isBind_tb = false;
  HDKListModelData hdkmodel;
  _ShopDetailPageState(this.hdkmodel);
  List bannerData = []; //轮播图数组
  String title = ''; //商品名称
  var zk_final_price = ''; //商品折扣价格
  var reserve_price; //商品一口价格
  var coupon_amount; //	优惠券面额
  var volume; //	30天销量
  String pict_url = '';
  String nick = ''; //卖家名称
  String coupon_click_url = '';
  var commission; //	佣金
  var commission_vip; //	VIP佣金
  Map goods_details = new Map();
  bintTb(String uid) async {
    //获取推荐人信息
    Map map = new Map();
    uid=uid.substring(uid.length-6);
    map['token'] = token;
    List<String> lists=uid.split("");
    map['tb_uid']=lists[0]+lists[1]+lists[4]+lists[5]+lists[2]+lists[3];
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.BindingTaobaoUrl, data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Fluttertoast.showToast(msg: msg);
    if (code == 1 && mounted) {
      setState(() {
        isBind_tb = true;
      });
    } else {}
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar:
      //     PreferredSize(child: AppBar(), preferredSize: Size.fromHeight(0)),
      appBar: new AppBar(
        title: Text('商品详情',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
      ),
      body: title == ''
          ? Container()
          : Stack(children: <Widget>[
              Container(
                  height: ScreenUtil.getInstance().setHeight(1334) +
                      kWindowstateHeight +
                      56,
                  child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[
                        _buildBanner(),
                        Container(
                            margin: EdgeInsets.all(
                                ScreenUtil.getInstance().setWidth(15)),
                            child: Text(
                              title,
                              style: TextStyle(fontSize: 17),
                            )),
                        Container(
                          margin: EdgeInsets.all(
                              ScreenUtil.getInstance().setWidth(15)),
                          child: Row(
                            children: <Widget>[
                              Container(
                                decoration: new BoxDecoration(
                                  color: Colors.red,
                                  //设置四周圆角 角度
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(4.0)),
                                  //设置四周边框
                                  border: new Border.all(
                                      width: 1, color: Colors.red),
                                ),
                                alignment: Alignment.center,
                                width: 60,
                                height: 20,
                                child: Text(
                                  '券后价',
                                  style: TextStyle(color: Colors.white),
                                ),
                                // color: Colors.red,
                              ),
                              Expanded(
                                  child: RichText(
                                textAlign: TextAlign.left,
                                text: TextSpan(
                                    style: TextStyle(color: Colors.red),
                                    children: [
                                      TextSpan(
                                          text: '¥',
                                          style: TextStyle(fontSize: 12.0)),
                                      TextSpan(
                                          text: zk_final_price == null
                                              ? '0'
                                              : zk_final_price.toString(),
                                          style: TextStyle(fontSize: 18.0)),
                                      TextSpan(
                                        text: reserve_price == null
                                            ? '0'
                                            : reserve_price.toString(),
                                        style: TextStyle(
                                            fontSize: 12.0,
                                            color: Colors.grey,
                                            decoration:
                                                TextDecoration.lineThrough,
                                            decorationColor: Colors.grey),
                                      ),
                                    ]),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              )),
                              Expanded(
                                  flex: 1,
                                  child: Container(
                                    margin: EdgeInsets.fromLTRB(
                                        ScreenUtil.getInstance().setWidth(20),
                                        0,
                                        ScreenUtil.getInstance().setWidth(20),
                                        0),
                                    height:
                                        ScreenUtil.getInstance().setWidth(34),
                                    color: Color.fromRGBO(250, 226, 226, 1),
                                    child: Center(
                                        child: Text(
                                            '佣金¥' +
                                                (commission == null
                                                    ? '0'
                                                    : commission.toString()),
                                            style: TextStyle(
                                                color: Colors.red,
                                                fontSize: 10))),
                                  ))
                            ],
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.fromLTRB(
                              ScreenUtil.getInstance().setWidth(20),
                              0,
                              ScreenUtil.getInstance().setWidth(20),
                              0),
                          alignment: Alignment.centerLeft,
                          child: Text(nick),
                        ),
                        Container(
                          margin: EdgeInsets.all(
                              ScreenUtil.getInstance().setWidth(20)),
                          child: Text('商品详情'),
                        ),
                        Container(
                            // 使用可提供高度的Container包裹WebView, 设置为回调的高度
                            height: _htmlHeight,
                            child: WebView(
                                initialUrl:
                                    'https://mdetail.tmall.com/templates/pages/desc?id=' +
                                        hdkmodel.itemid,
                                javascriptMode: JavascriptMode.unrestricted,
                                onWebViewCreated:
                                    (WebViewController controller) {
                                  _controller = controller;
                                  controller.canGoBack().then((res) {
                                    print(res); // 是否能返回上一级
                                  });
                                  controller.currentUrl().then((url) {
                                    print(url); // 返回当前url
                                  });
                                  controller.canGoForward().then((res) {
                                    print(res); //是否能前进
                                  });
                                  // _setJSHandler(_controller);
                                },
                                onPageFinished: (String value) {
                                  // webview 页面加载调用
                                  // _controller.evaluateJavascript(
                                  //     "window.flutter_inappbrowser.callHandler('InAppWebView', document.body.scrollHeight));");
                                },
                                navigationDelegate:
                                    (NavigationRequest request) {
                                  // if (request.url
                                  //     .startsWith('https://www.baidu.com')) {
                                  //   // 做一些事情
                                  //   // 阻止进入登录页面
                                  //   return NavigationDecision.prevent;
                                  // }
                                  return NavigationDecision.navigate;
                                })
                            // InAppWebView(
                            //   initialUrl:
                            //       'https://mdetail.tmall.com/templates/pages/desc?id=' +
                            //           hdkmodel.itemid,
                            //   initialHeaders: {},
                            //   initialOptions: InAppWebViewWidgetOptions(
                            //       inAppWebViewOptions: InAppWebViewOptions(
                            //     debuggingEnabled: true,
                            //   )),
                            //   onWebViewCreated: (InAppWebViewController controller) {
                            //     webView = controller;
                            //   },
                            //   onLoadStart:
                            //       (InAppWebViewController controller, String url) {
                            //     setState(() {
                            //       this.url = url;
                            //     });
                            //   },
                            //   onLoadStop: (InAppWebViewController controller,
                            //       String url) async {
                            //         print(controller.getHtml().toString());
                            //         webView.evaluateJavascript();
                            //     setState(() {
                            //       this.url = url;
                            //     });
                            //   },
                            //   onProgressChanged: (InAppWebViewController controller,
                            //       int progress) {},
                            // ),
                            )
                      ],
                    ),
                  )),
              // Positioned(
              //   top: kMargin10*3,
              //   left: kMargin10*3,
              //   child: IconButton(
              //       icon: ImageIcon(AssetImage("images/icon_detail_back.png")),
              //       onPressed: () {
              //         Navigator.pop(context);
              //       }),
              // ),
            ]),
      bottomNavigationBar: BottomAppBar(
          child: Row(
        children: <Widget>[
          Expanded(
              flex: 2,
              child: RaisedButton.icon(
                label: Text('分享'),
                icon: Icon(Icons.share),
                color: Colors.yellow,
                onPressed: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          //导航打开新视图
                          builder: (context) => GoodSharePage(
                              goods_details:
                                  goods_details) //打开第二个页面，并传值，传递值的名称是model
                          ));
                },
              )),
          Expanded(
              flex: 3,
              child: RaisedButton.icon(
                label: Text('领券'),
                icon: Icon(Icons.receipt),
                color: Colors.red,
                onPressed: () async {
                  if (!isBind_tb) {
                    Fluttertoast.showToast(msg: "请先绑定淘宝");
                    var result = await FlutterAlibc.loginTaoBao();
                    if (result.errorCode != "0") {
                      Fluttertoast.showToast(msg: result.errorMessage);
                      return;
                    }
                    showDialog(
                        context: context,
                        barrierDismissible: false,
                        builder: (_) {
                          return new NetLoadingDialog(
                            loadingText: "绑定中...",
                            bgColor: Color.fromARGB(255, 0, 0, 0),
                            requestCallBack: null,
                            outsideDismiss: false,
                          );
                        });
                    bintTb(result.data.openId);
                    return;
                  }
                  _getCreateTpwd();
                },
              ))
        ],
      )),
    );
  }

  _launchURL() async {
    if (Platform.isAndroid) {
      const platform = MethodChannel("com.example.flutter_yres/update");
      try {
        // 调用app地址
        platform.invokeMethod(
            'taobao', {"bundleId": "com.example.flutter_yres", "path": "path"});
      } on PlatformException catch (_) {}
    } else {
      // print(coupon_click_url);
      String url = "taobao://";
      if (await canLaunch(url)) {
        await launch(url);
      } else {
        throw 'Could not launch $url';
      }
    }
  }

//轮播图组件
  _buildBanner() {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(750),
      height: ScreenUtil.getInstance().setWidth(750),
      child: Swiper(
        itemBuilder: _swiperBuilder,
        itemCount: bannerData.length,
        loop: false,
        autoplay: true,
        autoplayDelay: 15000,
        pagination: new SwiperPagination(
            builder: DotSwiperPaginationBuilder(
          color: Colors.black54,
          activeColor: Colors.white,
        )),
        scrollDirection: Axis.horizontal,
        onTap: (index) {
          //点击轮播图事件
        },
      ),
    );
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return (Image.network(
      bannerData[index],
      fit: BoxFit.fill,
    ));
  }

  @override
  void initState() {
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      _getLoginMsg();
      isBindTb();
    });
    APPLIC.eventBus.on<LoginEvent>().listen((event) {
      getString(TOKEN).then((value) {
        token = value;
        _getLoginMsg();
        isBindTb();
      });
    });
  }

  isBindTb() async {
    //获取推荐人信息
    Map map = new Map();
    map['token'] = token;
    // map['sign_type'] = SignType.FREEZE_ACCOUNT;
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.WhetherBindingTaobaoUrl, data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    if (code == 1 && mounted) {
      setState(() {
        isBind_tb = userMap['data']['is_binding'] == "Y";
      });
    } else {}
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _getLoginMsg() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    token = preferences.get("token");
    print(token);
    print(this.hdkmodel.itemid);
    if (token == null || token == '') {
      //未登陆
      Navigator.of(context).pushNamed("login");
    } else {
      _getDetailUrl(this.hdkmodel.itemid, token);
    }
  }

//商品详情
  _getDetailUrl(String num_iid, String token) async {
    FormData data = new FormData.fromMap({'num_iid': num_iid, 'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetGoodsMsgUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    String msg = userMap["msg"];
    Fluttertoast.showToast(msg: msg);
    if (userMap['code'] == 1) {
      List banner = [];
      if (mounted) {
        Map goods_det = userMap['data'];

        if (goods_det['small_images'] == null) {
          banner.add(goods_det['pict_url']);
        } else {
          var small_images = goods_det['small_images']['string'];

          if (small_images is List) {
            banner = small_images;
          } else {
            banner.add(small_images);
          }
        }

        setState(() {
          goods_details = goods_det;
          bannerData = banner;
          title = goods_details['title'];
          zk_final_price = goods_details['zk_final_price']; //商品折扣价格
          reserve_price = goods_details['reserve_price']; //商品一口价格
          coupon_amount = goods_details['coupon_amount']; //	优惠券面额
          volume = goods_details['volume']; //	30天销量
          nick = goods_details['nick'].toString(); //卖家名称
          commission = goods_details['commission'];
          coupon_click_url = goods_details['coupon_click_url'];
          pict_url = goods_details['pict_url'];
          print(coupon_click_url);
        });
      }
    } else if (userMap['code'] == 105) {
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new LoginPage();
      }));
    } else {}
  }

  _getCreateTpwd() async {
    var result = await FlutterAlibc.openByUrl(
                    url:coupon_click_url,	//必须参数
                    openType : AlibcOpenType.AlibcOpenTypeNative,
                    isNeedCustomNativeFailMode : false,
                    nativeFailMode :    AlibcNativeFailMode.AlibcNativeFailModeNone,
                    schemeType : AlibcSchemeType.AlibcSchemeTaoBao,
                    backUrl:"",
                    );
    // FormData data = new FormData.fromMap({
    //   'url': coupon_click_url,
    //   'token': token,
    //   'text': title,
    //   'logo': pict_url
    // });
    // Response<String> response =
    //     await HttpUtil().post(Api.CreateTpwdUrl, data: data);
    // Map userMap = json.decode(response.data);
    // print(userMap);
    // if (userMap['code'] == 1) {
    //   Clipboard.setData(ClipboardData(text: userMap['data']));
    //   _launchURL();
    // }
  }
}
